package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a15_全排列
 * </p>
 *
 * @author flyduck
 * @since 2025-01-04
 */
public class a15_全排列 {

    public static void main(String[] args) {
        a15_全排列 test = new a15_全排列();
        int[] nums = new int[]{1,2,3};
        List<List<Integer>> permute = test.permute(nums);
        System.out.println("permute = " + permute);
    }

    //1,2,3
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[nums.length];
        traversal(result, path, nums, used);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int[] nums,
                           boolean[] used){
        if(path.size() == nums.length){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if(used[i]){
               continue;
            }
            path.add(nums[i]);
            used[i] = true;
            traversal(result, path, nums,used);
            path.removeLast();
            used[i] = false;
        }
    }


}
